package com.wxapp.custom.service.service.impl;

import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.wxapp.common.base.util.jackson.JacksonUtil;
import com.wxapp.common.base.util.redis.RedisUtil;
import com.wxapp.common.constant.base.IBaseService;
import com.wxapp.common.constant.constant.LoginConstant;
import com.wxapp.common.constant.pojo.vm.ResultVm;
import com.wxapp.common.constant.pojo.vo.UserVo;
import com.wxapp.common.constant.properties.LoginProperties;
import com.wxapp.common.util.check.CheckUtil;
import com.wxapp.common.util.condition.ConditionUtil;
import com.wxapp.common.util.copy.CopyUtil;
import com.wxapp.common.util.random.RandomUtil;
import com.wxapp.custom.api.pojo.entity.CustomDO;
import com.wxapp.custom.api.enums.listener.ListenerEnum;
import com.wxapp.custom.api.pojo.vm.custom.PCustomDetailVm;
import com.wxapp.custom.api.pojo.vm.custom.PCustomPageVm;
import com.wxapp.custom.api.pojo.vo.custom.QCustomPageVo;
import com.wxapp.custom.api.pojo.vo.custom.QCustomUpdateVo;
import com.wxapp.custom.api.pojo.vo.listener.ListenerVo;
import com.wxapp.custom.service.event.StatEvent;
import com.wxapp.custom.service.mapper.CustomMapper;
import com.wxapp.custom.service.service.CustomService;
import lombok.RequiredArgsConstructor;
import org.springframework.context.ApplicationEventPublisher;
import org.springframework.stereotype.Service;

import java.time.LocalDateTime;
import java.util.HashMap;
import java.util.Map;

/**
 * @author lgl
 * @Description
 * @Datetime 2023/10/7 10:08
 * @Modified By
 */
@Service
@RequiredArgsConstructor
public class CustomServiceImpl extends IBaseService implements CustomService {
    private final CustomMapper customMapper;
    private final LoginProperties loginProperties;
    private final RedisUtil redisUtil;
    private final ApplicationEventPublisher publisher;
    @Override
    public ResultVm<String> updateCustom(UserVo userVo, QCustomUpdateVo vo) {
        var query = new LambdaQueryWrapper<CustomDO>();
        query.eq(CustomDO::getUserId, userVo.getId())
                .eq(CustomDO::getStatus, true)
                .eq(CheckUtil.isNotNullString(vo.getId()), CustomDO::getId, vo.getId());
        var custom = customMapper.selectFirst(query);
        if (CheckUtil.isNullObject(custom)) {
            return error("没有找到用户信息");
        }
        CopyUtil.copyObject(vo, custom, (s, r) -> {
            r.setUpdateBy(userVo.getId());
            return null;
        });
        customMapper.updateById(custom);
        return success("更新成功");
    }

    @Override
    public ResultVm<PCustomDetailVm> detailCustom(UserVo userVo, String id) {
        var query = new LambdaQueryWrapper<CustomDO>();
        query.eq(CheckUtil.isNotNullString(id), CustomDO::getUserId, userVo.getId())
                .eq(CheckUtil.isNotNullString(id), CustomDO::getId, id)
                .eq(CheckUtil.isNotNullString(userVo.getCode()), CustomDO::getOpenId, userVo.getCode())
                .eq(CustomDO::getStop, false)
                .eq(CustomDO::getStatus, true);
        var custom = customMapper.selectFirst(query);
        if (custom == null || custom.getUserId().equals(userVo.getId())) {
            if (CheckUtil.isNullString(userVo.getLoginName())) {
                return error("获取详情失败");
            }
            custom = saveUpdateCustom(custom,userVo.getCode(), userVo.getId());
        }
        if (CheckUtil.isNullString(id)) {
            var ridesOpenId = redisUtil.get(LoginConstant.CUSTOM_OPENID + userVo.getId());
            if (CheckUtil.isNullObject(ridesOpenId)) {
                Map<String, String> map = new HashMap();
                map.put("customId", custom.getId());
                map.put("openId", userVo.getCode());
                redisUtil.set(LoginConstant.CUSTOM_OPENID + userVo.getId(), map, loginProperties.getExpireTime());
            }
        }
        return success(CopyUtil.copyObjectNew(custom, PCustomDetailVm::new, null));
    }

    @Override
    public ResultVm<Page<PCustomPageVm>> pageCustom(QCustomPageVo vo) {
        var page = ConditionUtil.getPage(vo, PCustomPageVm.class);
        var result = customMapper.selectCustomPage(page, vo);
        return success(result);
    }
    private CustomDO saveUpdateCustom(CustomDO customDO,String openId, String userId) {
        if (CheckUtil.isNotNullObject(customDO)){
            customDO.setUserId(userId);
            customMapper.updateById(customDO);
            return customDO;
        }
        var custom = new CustomDO();
        custom.setName(RandomUtil.getAllRandom(6));
        custom.setCreateTime(LocalDateTime.now());
        custom.setOpenId(openId);
        custom.setUserId(userId);
        custom.setStop(false);
        customMapper.insert(custom);
        publisher.publishEvent(new StatEvent(this,"用户",new ListenerVo(ListenerEnum.CUSTOMS, JacksonUtil.toJSONString(custom))));
        return custom;
    }
}
